package com.cloudlinkscm.loms.services.base.notify.domain;

import com.cloudlinkscm.loms.services.base.notify.constant.SendStatusEnum;
import com.cloudlinkscm.loms.services.base.notify.dao.MessageFlowDao;
import com.cloudlinkscm.loms.services.base.notify.dto.SendResultDto;
import com.cloudlinkscm.loms.services.base.notify.model.entity.Message;
import com.cloudlinkscm.loms.services.base.notify.model.entity.MessageFlow;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * @author : tac
 * @date : 2017/6/16
 */
public abstract class AbstractMessageFlowManager<MESSAGE extends Message> {
    private MessageFlowDao dao;

    public AbstractMessageFlowManager(MessageFlowDao dao) {
        this.dao = dao;
    }

    public String insert(MESSAGE message, SendResultDto result){
        MessageFlow o = new MessageFlow();
        o.setMessageId(message.getId());
        o.setType(getMessageType());
        o.setErrorMsg(result.getMsg());
        o.setSuccess(result.getState().equals(SendStatusEnum.SENT.val));
        o.setNum(generateUniqueNum());
        int rowNum = dao.insert(o);
        if(rowNum > 0){
            return o.getId();
        }
        return null;
    }

    private String generateUniqueNum() {
        return "MF" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + new Random().nextInt(10000000);
    }

    protected abstract String getMessageType();
}
